package com.zhang.gulimall.authserver.web;

import com.alibaba.fastjson.JSON;
import com.zhang.gulimall.authserver.constant.ClientConstant;
import com.zhang.gulimall.common.vo.GiteeUser;
import com.zhang.gulimall.authserver.feign.MemberFeign;
import com.zhang.gulimall.authserver.vo.TokenVo;
import com.zhang.gulimall.common.utils.HttpUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeign memberFeign;

    @RequestMapping("/oauth2/success")
    public String oauth2(@RequestParam("code") String code, HttpSession session) throws Exception {
        // 1.根据code获取token
        HashMap<String, String> map = new HashMap<>();
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://localhost:15000/oauth2/success"); // 回调地址
        map.put("code", code); // 授权码
        map.put("client_id", ClientConstant.clientId); // 服务器id
        map.put("client_secret", ClientConstant.clientSecret); // 服务器秘钥

        // 获取token
        String res = HttpUtils.post("https://gitee.com/oauth/token", map);
        if (res == null) {
            return "redirect:http://localhost:15000/login.html";
        }
        TokenVo tokenVo = JSON.parseObject(res, TokenVo.class);
        // 根据token获取用户信息
        String s = HttpUtils.get("https://gitee.com/api/v5/user?access_token=" + tokenVo.getAccess_token());
        if (s == null) {
            return "redirect:http://localhost:15000/login.html";
        }

        GiteeUser user = JSON.parseObject(s, GiteeUser.class);

        session.setAttribute("loginUser", user);

        BeanUtils.copyProperties(tokenVo, user);
        memberFeign.socialLogin(user);
        return "redirect:http://localhost:8000";
    }
}
